<?php

namespace control;
use JetBrains\PhpStorm\Language;

class toolCollectionClass extends adIndexClass
{
    private const page = 'toolCollection';
    private const table = 'tool_collection';
    private const tableMx = 'tool_collection_detail';
    private const tableReturn = 'tool_collection_return';
    private const tableRecord = 'inventory_record';
    private const title = '工具领用单';
    private const state = [1 => '未归还', 2 => '部分归还', 3 => '已归还', 0 => '草稿'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {

        switch ($fun) {
            case 'toolCollectionRecordSearch':
                $tr = [
                    'code'          => [
                        'name'  => '{l.toolCollection.edit.code}',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'name' => [
                        'name'  => '{l.toolCollection.edit.name}',
                        'width' => 150,
                    ],
                    'typeName'  => [
                        'name'  => '{l.toolCollection.addMx.type}',
                        'width' => 100,
                    ],
                    'model'  => [
                        'name'  => '{l.toolCollection.edit.model}',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'unit'  => [
                        'name'  => '{l.toolCollection.edit.unit}',
                        'width' => 80,
                    ],
                    'orderNo'         => [
                        'name'  => '{l.toolCollection.homeSearch.orderNo}',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'recipient'          => [
                        'name'  => '{l.toolCollection.edit.recipient}',
                        'width' => 100,
                    ],
                    'type'          => [
                        'name'  => '{l.toolCollection.edit.type}',
                        'width' => 100,
                    ],
                    'warehouse'          => [
                        'name'  => '{l.toolCollection.edit.warehouse}',
                        'width' => 150,
                    ],
                    'position'          => [
                        'name'  => '{l.toolCollection.edit.position}',
                        'width' => 150,
                    ],
                    'orderDate'          => [
                        'name'  => '{l.toolCollection.edit.orderDate}',
                        'width' => 150,
                    ],
                    'pickNum'          => [
                        'name'  => '{l.toolCollection.edit.pickNum}',
                        'width' => 100,
                    ],
                    'returnTime'          => [
                        'name'  => '{l.toolCollection.returnRecord.returnTime}',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'num'          => [
                        'name'  => '{l.toolCollection.returnRecord.returnNum}',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'batch'          => [
                        'name'  => '{l.toolCollection.edit.batch}',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '{l.toolCollection.detail.state}',
                        'width' => 100,
                    ]
                ];
                break;
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '{l.toolCollection.homeSearch.orderNo}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => '{l.toolCollection.edit.type}',
                        'width' => 200,
                    ],
                    'recipient'  => [
                        'name'  => '{l.toolCollection.homeSearch.recipient}',
                        'width' => 300,
                    ],
                    'orderDate'  => [
                        'name'  => '{l.toolCollection.homeSearch.orderDate}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'num'  => [
                        'name'  => '{l.toolCollection.homeSearch.num}',
                        'width' => 200,
                    ],
                    'text'         => [
                        'name'  => '{l.toolCollection.homeSearch.text}',
                        'width' => 200,
                    ],
                    'state'          => [
                        'name'  => '{l.toolCollection.homeSearch.state}',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('toolCollection.home.orderNo') => text(array("name" => "orderNo")),
                    L('toolCollection.home.recipient') => text(array("name" => "recipient")),
                    L('toolCollection.home.orderDate') => text(['name' => 'orderDate', 'laydate' => ['range' => '~', 'type' => 'date'],]),
                ],
                [
                    L('toolCollection.home.state') => select(["name" => "state", 'option' => self::state]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . L('toolCollection.homeSearch.detail') . "','" . $url . "&fun=edit')\" class='spanButton'>" . L('toolCollection.homeSearch.collect') . "</span>\n";
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'batchReturn'})\">" . L('toolCollection.homeSearch.batchReturn') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('toolCollection.homeSearch.del') . "</span>\n";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //查询结果
        $where = " coid = '" . self::$coid . "' ";
        $equal = [
            'state' => $this->post('state'),
        ];
        $like  = [
            'orderNo' => $this->post('orderNo'),
        ];
        //生成查询语句
        $where .= search([
            "="    => $equal,
            "like" => $like,
        ]);
        if ($this->post('orderDate')) {
            $where .= self::timeComparison($this->post('orderDate'), 'date', 'orderDate');
        }
        if ($this->post('recipient')) {
            $where .= " and recipient in (select stid from staff where name like '%" . $this->post('recipient') . "%') ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page                        = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['sql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate   = [
                "box"    => ["name" => "listId", "value" => $array['id'],],
                "detail" => ["title" => L('toolCollection.homeSearch.detail'), "click" => "newIframe('" . L('toolCollection.homeSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')",],
                "edit"   => ($array['state'] == '草稿') ? ["title" => L('toolCollection.homeSearch.edit'), "click" => "newIframe('" . L('toolCollection.homeSearch.detail') . "','" . $url . "&fun=edit&id=" . $array['id'] . "')",] : [],
            ];
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'recipient':
                        $recipient  = self::findStaff($array['recipient']);
                        $row[] = $recipient;
                        break;
                    case 'num':
                        $collection = find(array("table" => self::tableMx, "single" => "orderId = '" . $array['id'] . "'", "field" => " IFNULL(sum(num),0) as num "));
                        $row[] = self::lostZero($collection['num'], 'numPrecision');
                        break;
                    case 'state':
                        $row[] = self::state[$array['state']];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::tableMx,
            'single' => "orderId in (select id from ".self::table." where {$where})",
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = L('toolCollection.homeSearch.power');
        } else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $collection = find(array("table" => self::tableMx, "single" => "orderId = '" . $array['id'] . "'", "field" => " IFNULL(sum(num),0) as num "));
                $recipient  = self::findStaff($array['recipient']);
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '单据编号'=>$array['orderNo'],
                            '领用人'=>$recipient,
                            '领用日期'=>$array['orderDate'],
                            '领用数量'=>$collection['num'],
                            '备注'=>$array['text'],
                            '状态'=>self::state[$array['state']],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }

            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('toolCollection.homeSearch.log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title . ".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $id       = $this->get('id');
        $info     = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name"  => L('toolCollection.edit.save'),
            "type"  => "点击事件",
            "title" => L('toolCollection.edit.save'),
            'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        $tr[]     = ['', '{l.toolCollection.edit.code}', '{l.toolCollection.edit.name}', '{l.toolCollection.edit.model}', '{l.toolCollection.edit.unit}', '<div class="warehouse">' . '{l.toolCollection.edit.warehouse}' . self::chooseWarehouse(callback: 'getPosition') . '</div>', '{l.toolCollection.edit.position}', '{l.toolCollection.edit.batch}', '{l.toolCollection.edit.inventory}', '{l.toolCollection.edit.pickNum}'];
        $result   = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
        $totalArr = ['stock'=>0];
        foreach ((array)$result['array'] as $k=>$array) {
            $material = query('material', " id = '$array[materialId]'");
            $position = selectMultiple(["name" => "positionId[]", 'option' => self::positionOption($material['id'], $array['warehouseId']), 'title' => L('toolCollection.edit.choice'), 'change' => 'getBatch', 'value' => $array['positionId']]);
            $batch    = selectMultiple(["name" => "batch[]", 'option' => self::getBatchOption($material['id'], $array['warehouseId'], $array['positionId']), 'title' => L('toolCollection.edit.choice'), 'change' => 'getStock', 'value' => $array['batch']]);
            $stock    = inventoryBalanceClass::inventoryNum($array['materialId'], $array['warehouseId'], $array['positionId'], $array['batch']);
            $tr[]     =
                [
                    componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                    hidden(['name' => 'mxId[]', 'value' => $array['id']]) .
                    hidden(['name' => 'materialId[]', 'value' => $array['materialId'],]),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    idSelect(array(
                        'name'     => 'warehouseId[]',
                        'sqlForm'  => "warehouse WHERE coid = '" . self::$coid . "' and state = '启用' " . self::getWarehouseSql(),
                        'sqlId'    => 'id',
                        'sqlField' => "name",
                        'title'    => L('toolCollection.edit.warehouse'),
                        'change'   => 'getPosition',
                        'value'    => $array['warehouseId']
                    )),
                    "<span class='position'>$position</span>",
                    "<span class='batch'>$batch</span>",
                    "<span class='stock'>$stock</span>",
                    text(['name' => 'num[]', 'blur' => 'calculateTotal', 'value' => self::lostZero($array['num'], 'numPrecision'), 'other' => self::digitalFiltering('numPrecision')]),
                ];
            $totalArr['stock'] += $stock;
        }
        $total = [
            8 => "<span id='total_stock'>".self::lostZero($totalArr['stock'],'numPrecision')."</span>",
            9 => "<span id='total_num'>".self::lostZero(array_sum(array_column($result['array'],'num')),'numPrecision')."</span>",
        ];
        $list  = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
        $page  = self::page;
        $but   = "<span class='smallButton' onclick=\"layer('{$this->get('cla')}','addMx', $('form[name={$page}EditForm]').serialize())\">" . L('toolCollection.edit.choiceMaterial') . "</span>";
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . L('toolCollection.edit.type') . "："      => selectMultiple([
                        "name"   => "type",
                        "value"  => $info['type'],
                        'option' => explode('，', para('collectionType')),
                        'title'  => L('toolCollection.edit.choice')
                    ]),
                    must . L('toolCollection.edit.recipient') . "：" => selectMultiple([
                        "name"     => "recipient",
                        "value"    => $info['recipient'],
                        'table'    => "staff",
                        'sqlId'    => 'stid',
                        'sqlField' => 'name',
                        'title'    => L('toolCollection.edit.choice')
                    ]),
                    must . L('toolCollection.edit.orderDate') . "：" => text(["name" => "orderDate", 'laydate' => [], "value" => $info['orderDate'] ?: $this->date]),
                ],
                [
                    L('toolCollection.edit.text')                   => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => L('toolCollection.edit.pickMx'),
            'button' => $but,
            'html' => $list,
        ]);
        $data['html'] = $this->pageEdit([
            "html"  => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $cla          = self::page;
        $data['html'] .= <<<efo
<script>
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
        $("#materialTable tbody").append(res.html);
        resetNumber($("#materialTable"))
    },'json');
}
//根据仓库获取库位
function getPosition(e){
    let warehouseId = e.value;
    let materialId = $(e).parent().parent().find("[name='materialId[]']").val();
    $.post(root+'control/adIndex.html?cla={$cla}&fun=getPosition',{warehouseId:warehouseId,materialId:materialId},function(res) {
          $(e).parent().parent().find(".position").html(res.position);
    },'json');
}
//根据库位获取批次
function getBatch(e){
    let positionId = e.value;
    let par = $(e).parents("tr")
    let warehouseId = par.find("[name='warehouseId[]']").val();
    let materialId = par.find("[name='materialId[]']").val();
    $.post(root+'control/adIndex.html?cla={$cla}&fun=getBatch',{positionId:positionId,warehouseId:warehouseId,materialId:materialId},function(res) {
          par.find(".batch").html(res.batch);
    },'json');
}
//根据批次获取库存
function getStock(e){
    let batch = e.value;
    let par = $(e).parents("tr")
    let positionId = par.find("[name='positionId[]']").val();
    let warehouseId = par.find("[name='warehouseId[]']").val();
    let materialId = par.find("[name='materialId[]']").val();
    $.post(root+'control/adIndex.html?cla={$cla}&fun=getStock',{warehouseId:warehouseId,positionId:positionId,materialId:materialId,batch:batch},function(res) {
          par.find(".stock").html(res.stock);
          calculateTotal()
    },'json');
}
//计算总数量
function calculateTotal(){
    let table = $('.editList')
    let num = 0,
    stock = 0
    table.find("[name='num[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
        var stockText = table.find(".stock").eq(index).text()
        if(stockText){
            stock+=Number(stockText);
        }
    })
    $("#total_stock").text(stock.toFixed(publicSettings.numPrecision.num));
    $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
}
</script>

efo;
        //返回
        return $this->tab($data);
    }

    /** 库位选择
     *
     * @param string $materialId
     * @param string $warehouseId
     * @return array
     */
    public static function positionOption(string $materialId, string $warehouseId): array
    {
        $where            = "";
        $and              = " AND a.coid = '" . self::$coid . "' ";
        $like             = [];
        $equal            = [
            'a.materialId'  => $materialId,
            'a.warehouseId' => $warehouseId,
        ];
        $where            .= search([
                "like" => $like,
                "="    => $equal,
            ]) . $and;
        $fieldArr         = self::resolveField([
            'field' => 'a.`positionId`, b.name, SUM(a.num) as num',
            'group' => 'a.positionId',
        ]);
        $where            .= $fieldArr['group'] . " having sum(a.num)>0";
        $inventory_record = find([
            "table" => 'inventory_record as a join warehouse_position as b on a.positionId = b.id',
            'field' => $fieldArr['field'],
            "where" => $where . " order by sum(a.num) desc "
        ]);
        return array_column((array)$inventory_record['array'], 'name', 'positionId');
    }

    /** 获取批号
     * @param $materialId
     * @param string $warehouseId
     * @param string $positionId
     * @return array
     */
    public static function getBatchOption($materialId, $warehouseId = '', $positionId = ''): array
    {
        if (empty($warehouseId) || empty($positionId)) {
            return [];
        }
        $and = '';
        if ($positionId) {
            $and = " and positionId = '$positionId' ";
        }
        $where        = " 1=1 and materialId = '$materialId' and warehouseId = '$warehouseId' and coid = '" . self::$coid . "' {$and} ";
        $fieldArr     = self::resolveField([
            'field' => 'batch',
            'group' => 'batch',
        ]);
        $where        .= $fieldArr['group'];
        $outAllowZero = optionSettingClass::getSettingItem('库存', 'outAllowZero');//允许零库存出库
        $having       = "";
        if (!$outAllowZero) {
            $having = " having SUM(num) > 0 ";
        }
        $result = find([
            'table' => 'inventory_record',
            'field' => $fieldArr['field'],
            'where' => $where . $having . " order by SUM(num) desc",
        ]);
        $batch  = [];
        if (is_array($result['array'])) {
            $arr = array_column($result['array'], 'batch');
            foreach ((array)$arr as $val) {
                if (empty($val)) {
                    $batch[''] = '无';
                } else {
                    $batch[$val] = $val;
                }
            }
        }
        return $batch;
    }

    /** 根据仓库获取库位
     * @param string $warehouseId
     * @param string $materialId
     * @return mixed
     */
    public function getPosition($warehouseId = '', $materialId = ''): mixed
    {
        $warehouseId = $warehouseId ?: $this->post('warehouseId');
        $materialId  = $materialId ?: $this->post('materialId');
        //批号
        $json['position'] = selectMultiple([
            "name"   => "positionId[]",
            'option' => self::positionOption($materialId, $warehouseId),
            'title'  => L('toolCollection.edit.choice'),
            'change' => 'getBatch',
            'value'  => L('toolCollection.edit.choice')
        ]);
        return json_encode($json, 320);
    }

    /** 根据库位获取批次
     * @param string $warehouseId
     * @param string $positionId
     * @param string $materialId
     * @return mixed
     */
    public function getBatch($warehouseId = '', $positionId = '', $materialId = ''): mixed
    {
        $warehouseId = $warehouseId ?: $this->post('warehouseId');
        $positionId  = $positionId ?: $this->post('positionId');
        $materialId  = $materialId ?: $this->post('materialId');
        //批号
        $json['batch'] = selectMultiple([
            "name"   => "batch[]",
            'option' => self::getBatchOption($materialId, $warehouseId, $positionId),
            'title'  => L('toolCollection.edit.choice'),
            'change' => 'getStock',
            'value'  => '-1'
        ]);
        return json_encode($json, 320);
    }

    /**
     * 根据批次获取库存
     */
    public function getStock(): bool|string
    {
        $warehouseId = $this->post('warehouseId');
        $positionId  = $this->post('positionId');
        $materialId  = $this->post('materialId');
        $batch       = $this->post('batch');
        //批号
        $json['stock'] = inventoryBalanceClass::inventoryNum($materialId, $warehouseId, $positionId, $batch);
        return json_encode($json, 320);
    }


    /**
     * 选择仓库
     *
     * @return string
     */
    public static function chooseWarehouse(string $obj = '', string $callback = ''): string
    {
        $obj    = $obj ?: 'warehouseId';
        $result = find(array('table' => 'warehouse', 'where' => " coid = '" . self::$coid . "' AND state = '启用' " . self::getWarehouseSql() . " order by time desc"));
        $li     = '';
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                $li .= "<li data-id='$array[id]'>{$array['name']}</li>";
            }
        }
        if (empty($li)) {
            $li = "<li>" . L('toolCollection.chooseWarehouse.none') . "</li>";
        }
        $batchWord = L('toolCollection.chooseWarehouse.batch');
        return <<<EOT
        <span class='del-row-button' id='chooseWareHouse'>$batchWord</span><div class='stateBlock' style="margin-top: 7px;"><ul>$li</ul></div>
        <script>
         //点击非下拉区域隐藏
        $(document).bind('click', function (e) {
            let target = $(".stateBlock");
            let obj = $(".warehouse");
            if(!target.is(e.target) && target.has(e.target).length ===0 && !obj.is(e.target) && obj.has(e.target).length ===0){
              target.hide();
            }
        });
        $("#chooseWareHouse").on('click',function() {
           $(".stateBlock").show();
        })
        $(".warehouse .stateBlock li").on('click',function() {
            let id = $(this).data('id');
            $("select[name='{$obj}[]']").each(function() {
              let obj = $(this);
              obj.val(id);
              $callback(this)
            });
           $(".stateBlock").hide();
        })
        </script>    
EOT;
    }

    public function editEdit()
    {
        $id            = $this->post('id') ?: self::getId();
        $mxIdArr       = $this->post('mxId') ?: [];
        $materialIdArr = $this->post('materialId');
        $warehouseArr  = $this->post('warehouseId');
        $positionArr   = $this->post('positionId');
        $numArr        = $this->post('num');
        $batchArr      = $this->post('batch');

        $field      = [
            'type'      => $this->post('type'),
            'recipient' => $this->post('recipient'),
            'orderDate' => $this->post('orderDate'),
            'text'      => $this->post('text'),
        ];
        $annotation = [
            'type'      => L('toolCollection.edit.type'),
            'recipient' => L('toolCollection.editEdit.recipient'),
            'orderDate' => L('toolCollection.editEdit.orderDate'),
            'text'      => L('toolCollection.editEdit.text'),
        ];
        $rules      = [
            'type'      => 'required',
            'recipient' => 'required',
            'orderDate' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        //同一物料同一库位批次不可重复添加
        $tempBatchResult = [];
        foreach ((array)$materialIdArr as $k => $v) {
            if (isset($tempBatchResult[$v][$positionArr[$k]][$batchArr[$k]])) {
                $json['warn'] = str_replace(['{{i}}'], [($k + 1)], L('toolCollection.editEdit.repeat'));
                goto resp;
            }
            // 批次数量汇总
            $tempBatchResult[$v][$positionArr[$k]][$batchArr[$k]] = 1;
        }
        $where = " id = '$id' ";
        $info  = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('toolCollection.editEdit.power');
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = L('toolCollection.editEdit.outMx');
        } elseif (static::is_null_array($materialIdArr)) {
            $json['warn'] = L('toolCollection.editEdit.outMx');
        } elseif (static::is_null_array($warehouseArr)) {
            $json['warn'] = L('toolCollection.editEdit.warehouse');
        } elseif (static::is_null_array($positionArr)) {
            $json['warn'] = L('toolCollection.editEdit.position');
        } elseif (static::is_null_array($numArr)) {
            $json['warn'] = L('toolCollection.editEdit.num');
        } elseif (!empty($info['id']) && $info['state'] != 0) {
            $json['warn'] = L('toolCollection.editEdit.stateError');
        } else {
            $this->startTrans();
            $isPass = true;//事务通过标志
            if (!$info['id']) {
                $orderNo      = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'GJLY' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => " AND coid = '" . self::$coid . "' ",
                ], $field);
                $field        = array_merge($field, [
                    'id'      => $id,
                    'orderNo' => $orderNo,
                    'state'   => 0,
                    'coid'    => self::$coid,
                    'stid'    => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field,]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            //添加或更新报价单明细
            if (is_array($mxIdArr)) {
                foreach ($mxIdArr as $k => $nid) {
                    $mx         = query(self::tableMx, "id = '$nid'");
                    $material   = query('material', "id = '$materialIdArr[$k]'", "unit");
                    $numArr[$k] = self::formattingFigure($numArr[$k], 'numPrecision');
                    if (!empty($mx['id'])) {
                        //更新
                        $warn = static::update([
                            "table" => self::tableMx,
                            "field" => [
                                'warehouseId' => $warehouseArr[$k],
                                'positionId'  => $positionArr[$k],
                                'batch'       => $batchArr[$k],
                                'num'         => $numArr[$k],
                            ],
                            "where" => " id = '$nid'",
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => self::tableMx,
                            "field" => [
                                'id'          => $nid,
                                'coid'        => self::$coid,
                                'orderId'     => $id,
                                'materialId'  => $materialIdArr[$k],
                                'batch'       => $batchArr[$k],
                                'num'         => $numArr[$k],
                                'unit'        => $material['unit'],
                                'warehouseId' => $warehouseArr[$k],
                                'positionId'  => $positionArr[$k],
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                $this->commitTrans();
                delete(['table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"]);
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], L('toolCollection.editEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * @return string
     */
    public function addMx(): string
    {
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = '';
        $data             = [
            'sub'            => " onclick=\"addRow();$('#" . $layerId . "').remove()\" ",
            'continueAdding' => $notAllowRepeat ? " onclick=\"addRow();removeSelectedContent('" . $formName . "')\" " : " onclick=\"addRow();\" ",
            'hidden'         => hidden(['name' => 'notAllowRepeat', 'value' => $notAllowRepeat]),
        ];
        return $materialClassObj->addMx($data);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxIdArr = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('toolCollection.addMxEdit.power');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('toolCollection.addMxEdit.noChoice');
        } else {
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $material     = query('material', "id = '$mxId'");
                $id           = self::getId();
                $warehouseSel = idSelect(array(
                    'name'     => 'warehouseId[]',
                    'sqlForm'  => "warehouse WHERE coid = '" . self::$coid . "' AND state = '启用' " . self::getWarehouseSql(),
                    'sqlId'    => 'id',
                    'sqlField' => "name",
                    'title'    => '仓库',
                    'change'   => 'getPosition'
                ));
                $position     = selectMultiple([
                    "name"   => "positionId[]",
                    'option' => self::positionOption($material['id'], '##'),
                    'title'  => L('toolCollection.edit.choice'),
                    'change' => 'getBatch',
                    'value'  => ''
                ]);
                $batch        = selectMultiple([
                    "name"   => "batch[]",
                    'option' => self::getBatchOption($material['id'], '', ''),
                    'title'  => L('toolCollection.edit.choice'),
                    'change' => 'getStock',
                    'value'  => ''
                ]);
                $numFiltering = self::digitalFiltering('numPrecision');
                $tr[]     =
                    [
                        componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                        hidden(['name' => 'mxId[]', 'value' => $id]) .
                        hidden(['name' => 'materialId[]', 'value' => $mxId]),
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $material['unit'],
                        $warehouseSel,
                        "<span class='position'>$position</span>",
                        "<span class='batch'>$batch</span>",
                        "<span class='stock'></span>",
                        text(['name' => 'num[]', 'blur' => 'calculateTotal', 'value' => '', 'other' => self::digitalFiltering('numPrecision')]),
                    ];
            }
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}' ");
        if (empty($info['id'])) {
            $html = L('toolCollection.detail.empty');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == 0) {
                //按钮
                $button[] = [
                    "name" => L('toolCollection.homeSearch.del'),
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
                //按钮
                $button[] = [
                    "name"  => L('toolCollection.detail.edit'),
                    "type"  => "顶部页卡",
                    "title" => L('toolCollection.detail.editDetail'),
                    "url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    'style' => 'li-btn-blue-bg',
                ];
                $button[] = [
                    "name"  => L('toolCollection.detail.surePick'),
                    "type"  => "弹出层",
                    "cla"   => $this->get('cla'),
                    "fun"   => "operate",
                    "post"  => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            //操作记录
            $button[] = self::operateLogBut($info['id']);

            $mxtr[] = ['{l.toolCollection.detail.code}', '{l.toolCollection.detail.name}', '{l.toolCollection.detail.model}', '{l.toolCollection.detail.unit}', '{l.toolCollection.detail.warehouse}', '{l.toolCollection.edit.position}', '{l.toolCollection.detail.batch}', '{l.toolCollection.detail.pickNum}', '{l.toolCollection.detail.notReturn}', '{l.toolCollection.detail.operate}'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $material = query('material', " id = '$array[materialId]'");
                $mxBtn    = '';
                if (in_array($info['state'], [1, 2])) {
                    $mxBtn .= "<span class='del-row-button' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'return', 'id': '{$array['id']}' })\">" . L('toolCollection.detail.return') . "</span> ";
                }
                $mxBtn  .= " <span class='del-row-button'  onclick=\"layer('{$this->get('cla')}', 'returnRecord', { 'id': '" . $array['id'] . "'})\">" . L('toolCollection.detail.returnRecord') . "</span>";
                $mxtr[] = [
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    warehouseClass::getName($array['warehouseId']),
                    warehousePositionClass::getName($array['positionId']),
                    $array['batch'],
                    self::lostZero($array['num'], 'numPrecision'),
                    $array['num'] - $array['return_num'],
                    $mxBtn,
                ];
            }
            $total_tr = [
                7 => self::lostZero(array_sum(array_column($result['array'],'num')), 'numPrecision'),
                8 => self::lostZero(array_sum(array_column($result['array'],'num')) - array_sum(array_column($result['array'],'return_num')), 'numPrecision'),
            ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                [
                    [
                        L('toolCollection.detail.recipient') => self::findStaff($info['recipient']),
                        L('toolCollection.detail.orderDate') => $info['orderDate'],
                        L('toolCollection.detail.orderNo') => $info['orderNo'],
                        L('toolCollection.detail.stid')    => self::findStaff($info['stid']),
                    ],
                    [
                        L('toolCollection.detail.state')   => self::state[$info['state']]
                    ],
                    [
                        L('toolCollection.detail.text') => $info['text'],
                    ],
                ]
            ]);
            $data['html'] .= $this->detailList([
                'title' => L('toolCollection.detail.pickMx'),
                'html' => $this->listTable(array('tr' => $mxtr, 'showSort' => true, 'total' => $total_tr)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id    = $this->post('id');
        $info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
        $field = [
            'state'       => 1,
            'confirmTime' => $this->time
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('toolCollection.confirmEdit.power');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('toolCollection.confirmEdit.empty');
        } elseif ($info['state'] != 0) {
            $json['warn'] = L('toolCollection.confirmEdit.stateError');
        } else {
            $this->startTrans();
            $isPass = true; // 事务通过标志

            $json['warn'] = update([
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ]);
            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass === true) {
                /***收发明细***/
                $bool = $this->insertInventoryOut($info);
                if ($bool !== true) {
                    $json['warn'] = $bool;
                    goto resp;
                }
                $this->commitTrans();//提交事务
                auditingFollow(array(
                    "type"   => "工具领用单",
                    "typeId" => $info['id'],
                    "text"   => "【{$this->control['name']}】确认",
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], lang('toolCollection.confirmEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 生成出库单
     */
    private function insertInventoryOut($info): bool|string
    {
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
        $id     = self::getId();
        $field  = [
            'id'          => $id,
            'coid'        => self::$coid,
            'orderNo'     => codeTemplateClass::generateCode('outStock', [
                'prefix' => 'CKD' . date('Ymd'),
                'table'  => 'inventory_changes',
                'field'  => 'orderNo',
                'where'  => " and coid = '" . self::$coid . "'",
            ], []),
            'type'        => '其他出库',
            'classify'    => 0,
            'recordDate'  => $this->date,
            'confirmTime' => $this->date,
            'reviewTime'  => $this->date,
            'state'       => '已复核',
            'stid'        => self::$stid,
        ];
        $warn   = static::insert(array(
            'table' => 'inventory_changes',
            'field' => $field
        ));
        if ($warn != '新增成功') {
            return "新增出库单失败";
        }
        /***仓库允许零库存出库*/
        $outAllowZero = optionSettingClass::getSettingItem('库存', 'outAllowZero');
        foreach ($result['array'] as $mx) {
            $mx['price'] = inventoryDefaultClass::pricingRules('outStockPrice', $mx['materialId'], $mx['unit']);
            $num         = $mx['num'];
            $money       = self::formattingFigure($num * $mx['price']);
            $warn        = static::insert(array(
                'table' => 'inventory_changes_detail',
                'field' => $fieldChangeMx = [
                    'id'          => self::getId(),
                    'coid'        => self::$coid,
                    'orderId'     => $id,
                    'materialId'  => $mx['materialId'],
                    'orderNum'    => $num,
                    'batch'       => $mx['batch'],
                    'num'         => $num,
                    'unit'        => $mx['unit'],
                    'price'       => $mx['price'],
                    'money'       => $money,
                    'sourceTable' => 'tool_collection_detail',
                    'sourceId'    => $mx['id'],
                    'sourceNo'    => $info['orderNo'],
                    'warehouseId' => $mx['warehouseId'],
                    'positionId'  => $mx['positionId'],
                ]
            ));
            if ($warn != '新增成功') {
                return "新增出库单明细失败";
            }

            $value = $mx;
            // 转换主单位
            $mainUnitNum = inventoryBalanceClass::toMainUnit($value['materialId'], $value['num'], $value['unit']);
            $stock       = inventoryBalanceClass::inventoryNum($value['materialId'], $value['warehouseId'], $value['positionId'], $value['batch']);

            $bool = inventoryBalanceClass::inventoryControl($value['materialId'], $mainUnitNum, "down");  //最低库存控制
            if ($bool !== true) {
                return $bool;
            }
            // 判断库存
            if (!$outAllowZero && $stock - $mainUnitNum < 0) {
                return L('toolCollection.confirmEdit.transfinite');
            } elseif ($outAllowZero && $stock - $mainUnitNum < 0) {
                //发送负库存预警
                $setting = self::getSettingValue('inventoryNegative');
                foreach ($setting['member'] as $item) {
                    message(array(
                        "stid"      => $item,
                        "type"      => '预警消息',
                        "typeId"    => $value['materialId'],
                        "text"      => "物料【" . materialClass::getName($value['materialId']) . "】负库存预警",
                        "targetCla" => 'inventoryBalance',
                        "targetFun" => 'detail',
                    ));
                }
            }

            $warn = insert([
                'table' => self::tableRecord,
                'field' => [
                    'id'           => self::getNo(),
                    'coid'         => self::$coid,
                    'warehouseId'  => $value['warehouseId'],
                    'positionId'   => $value['positionId'],
                    'materialId'   => $value['materialId'],
                    'batch'        => $value['batch'],
                    'num'          => -1 * $mainUnitNum,
                    'changesId'    => $fieldChangeMx['id'],
                    'defaultPrice' => $mx['price'],
                ],
            ]);
            if ($warn != '新增成功') {
                return "新增入库明细失败";
            }
            if (!empty($value['positionId'])) {
                inventoryBalanceClass::recordStockToLocation('', ['materialId' => $value['materialId'], 'warehouseId' => $value['warehouseId'], 'positionId' => $value['positionId'], 'batch' => $value['batch']]);
            }
        }
        return true;
    }


    // 操作中转
    public function operate()
    {
        $act    = $this->post('act') ?? '';
        $id     = $this->post('id') ?? '';
        $pwd    = $word = $height = false; // 需要密码
        $append = [];
        switch ($act) {
            case 'confirm':
                $act      = 'edit';
                $msg      = L('toolCollection.operate.sure');
                $title    = L('toolCollection.operate.sureTitle');
                $function = 'confirmEdit';
                $form     = self::page . 'OperateForm, detailForm';
                $power    = '';
                $word     = true;
                break;
            case 'return':
                $act      = 'edit';
                $msg      = L('toolCollection.operate.return');
                $title    = '';
                $function = 'returnEdit';
                $word     = true;
                $info     = query(self::tableMx, " id = '$id' ");
                $num      = $info['num'] - $info['return_num'];
                $append   = [
                    [
                        must . L('toolCollection.operate.returnNum') . '：' => text(['name' => 'num', 'other' => self::digitalFiltering('numPrecision'), 'class' => 'text', 'value' => $num]) . hidden(['name' => 'id', 'value' => $info['id'],]),
                    ],
                ];
                $form     = self::page . 'OperateForm';
                $height   = 180;
                $power    = '';
                break;
            case 'batchReturn':
                $act      = 'edit';
                $msg      = L('toolCollection.operate.return');
                $title    = L('toolCollection.operate.sureBatchReturn');
                $function = 'batchReturn';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                $word     = true;
                break;
            default:
                $act      = 'del';
                $msg      = L('toolCollection.operate.del');
                $title    = self::page . 'Delete';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm, quoForm';
                $power    = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], lang('toolCollection.operate.log'));;
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
                'append'   => $append,
                'height'   => $height,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 批量归还
     *
     * @return bool|string
     */
    public function batchReturn()
    {
        $list = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('toolCollection.returnEdit.power');
        } elseif (empty($list)) {
            $json['warn'] = L('toolCollection.delete.noChoice');
        } else {
            $text     = "";
            $x        = 0;
            $list     = is_array($list) ? $list : [$list];
            $returnMx = [];
            $this->startTrans();
            foreach ($list as $id) {
                $info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
                if (!in_array($info['state'], [1, 2])) {
                    $text .= L('toolCollection.returnEdit.stateFail') . '【' . $info['orderNo'] . '】';
                } else {
                    $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
                    foreach ((array)$result['array'] as $array) {
                        $residue = (float)$array['num'] - (float)$array['return_num'];
                        if ($residue > 0) {
                            $material = query("material", " id = '" . $array['materialId'] . "' ");
                            $warn     = inventoryBalanceClass::inventoryControl($array['materialId'], $residue, "top");  //最高库存控制
                            if ($warn !== true) {
                                $json['warn'] = $warn;
                                goto resp;
                            }
                            if ($array['positionId']) {
                                $material['warehouse']  = $array['warehouseId'];
                                $material['positionId'] = $array['positionId'];
                            } elseif (empty($material['positionId']) || $material['warehouse'] != $array['warehouseId']) {
                                $material['positionId'] = inventoryBalanceClass::matchLocation($array['warehouseId']);
                                $material['warehouse']  = $array['warehouseId'];
                            }
                            $json['warn'] = static::insert([
                                'table' => self::tableReturn,
                                'field' => $returnMx[] = [
                                    'id'          => self::getId(),
                                    'coid'        => self::$coid,
                                    'orderId'     => $info['id'],
                                    'detail_id'   => $array['id'],
                                    'materialId'  => $array['materialId'],
                                    'batch'       => $array['batch'],
                                    'num'         => $residue,
                                    'unit'        => $array['unit'],
                                    'warehouseId' => $material['warehouse'],
                                    'positionId'  => $material['positionId'],
                                ],
                            ]);
                            if ($json['warn'] != '新增成功') {
                                $json['warn'] = '新增归还记录失败';
                                goto resp;
                            }
                        }
                    }
                    sqlExec(" UPDATE `" . self::tableMx . "` SET `return_num` = num WHERE orderId = '$info[id]' ");
                    //更改单据状态为已归还
                    static::update([
                        'table' => self::table,
                        'field' => [
                            'state' => 3,
                        ],
                        'where' => " id = '{$info['id']}' ",
                    ]);
                    //返回
                    $warn = L('toolCollection.returnEdit.success');
                    $x++;
                    $text .= str_replace(['{{id}}'], [$info['id']], lang('toolCollection.delete.text')) . $warn . "。<br>";
                }
            }
            /***收发明细***/
            $bool = $this->insertInventoryBatchIn($returnMx);
            if ($bool !== true) {
                $json['warn'] = $bool;
                goto resp;
            }
            $this->commitTrans();//提交事务
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], lang('toolCollection.returnEdit.log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], lang('toolCollection.returnEdit.warn'));
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 生成入库单
     */
    private function insertInventoryBatchIn($returnMx): bool|string
    {
        $id    = self::getId();
        $field = [
            'id'          => $id,
            'coid'        => self::$coid,
            'orderNo'     => codeTemplateClass::generateCode('inStock', [
                'prefix' => 'RKD' . date('Ymd'),
                'table'  => 'inventory_changes',
                'field'  => 'orderNo',
                'where'  => " and coid = '" . self::$coid . "'",
            ], []),
            'type'        => '其他入库',
            'classify'    => 1,
            'recordDate'  => $this->date,
            'confirmTime' => $this->date,
            'reviewTime'  => $this->date,
            'state'       => '已复核',
            'stid'        => self::$stid,
        ];
        $warn  = static::insert(array(
            'table' => 'inventory_changes',
            'field' => $field
        ));
        if ($warn != '新增成功') {
            return "新增入库单失败";
        }
        foreach ((array)$returnMx as $mx) {
            $info = query(self::table, " id = '$mx[orderId]' ");
            $warn = static::insert(array(
                'table' => 'inventory_changes_detail',
                'field' => $fieldChangeMx = [
                    'id'          => self::getId(),
                    'coid'        => self::$coid,
                    'orderId'     => $id,
                    'materialId'  => $mx['materialId'],
                    'orderNum'    => $mx['num'],
                    'batch'       => $mx['batch'],
                    'num'         => $mx['num'],
                    'unit'        => $mx['unit'],
                    'price'       => 0,
                    'sourceTable' => 'tool_collection_return',
                    'sourceId'    => $mx['id'],
                    'sourceNo'    => $info['orderNo'],
                    'warehouseId' => $mx['warehouseId'],
                    'positionId'  => $mx['positionId'],
                ]
            ));
            if ($warn != '新增成功') {
                return "新增入库变动明细失败";
            }
            //单位单价转换
            $mainUnitNum = inventoryBalanceClass::toMainUnit($mx['materialId'], $mx['num'], $mx['unit']);
            $recordId    = self::getNo();
            $warn        = insert([
                'table' => self::tableRecord,
                'field' => [
                    'id'            => $recordId,
                    'coid'          => self::$coid,
                    'warehouseId'   => $mx['warehouseId'],
                    'positionId'    => $mx['positionId'],
                    'materialId'    => $mx['materialId'],
                    'inventoryId'   => $id,
                    'inventoryMxId' => $fieldChangeMx['id'],
                    'batch'         => $mx['batch'],
                    'num'           => $mainUnitNum,
                    'changesId'     => $fieldChangeMx['id'],
                    'defaultPrice'  => inventoryBalanceClass::unitPrice($mx['materialId']),
                ],
            ]);
            if ($warn != '新增成功') {
                return "新增入库明细失败";
            }
            if (!empty($mx['positionId'])) inventoryBalanceClass::recordStockToLocation($recordId, ['positionId' => $mx['positionId']]);
        }
        return true;
    }

    /**
     * 归还入库
     */
    public function returnEdit()
    {
        $id        = $this->post('id');
        $num       = $this->post('num');
        $info      = query(self::tableMx, " id = '$id'");
        $res       = query(self::table, " id = '$info[orderId]' ");
        $material  = query("material", " id = '" . $info['materialId'] . "' ");
        $warn      = inventoryBalanceClass::inventoryControl($info['materialId'], $num, "top");  //最高库存控制
        $notReturn = $info['num'] - $info['return_num'];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('toolCollection.returnEdit.power');
        } elseif (empty($res['id'])) {
            $json['warn'] = L('toolCollection.returnEdit.empty');
        } elseif ($warn !== true) {
            $json['warn'] = $warn;
        } elseif (!in_array($res['state'], [1, 2])) {
            $json['warn'] = L('toolCollection.returnEdit.stateError');
        } elseif (abs($num) > $notReturn) {
            $json['warn'] = L('toolCollection.returnEdit.transfinite') . $notReturn;
        } else {
            $num = abs($num);
            $this->startTrans();
            $isPass       = false; // 事务通过标志
            $json['warn'] = static::update([
                "table" => self::tableMx,
                "field" => [
                    'return_num' => $info['return_num'] + $num,
                ],
                "where" => "id = '$info[id]'",
            ]);
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $isPass = true;
                if ($res['state'] == 1) {
                    static::update([
                        'table' => self::table,
                        'field' => [
                            'state' => 2,
                        ],
                        'where' => " id = '{$res['id']}' ",
                    ]);
                }
                if ($info['positionId']) {
                    $material['warehouse']  = $info['warehouseId'];
                    $material['positionId'] = $info['positionId'];
                } elseif (empty($material['positionId']) || $material['warehouse'] != $info['warehouseId']) {
                    $material['positionId'] = inventoryBalanceClass::matchLocation($info['warehouseId']);
                    $material['warehouse']  = $info['warehouseId'];
                }
                $json['warn'] = static::insert([
                    'table' => self::tableReturn,
                    'field' => $returnMx = [
                        'id'          => self::getId(),
                        'coid'        => self::$coid,
                        'orderId'     => $res['id'],
                        'detail_id'   => $info['id'],
                        'materialId'  => $info['materialId'],
                        'batch'       => $info['batch'],
                        'num'         => $num,
                        'unit'        => $info['unit'],
                        'warehouseId' => $material['warehouse'],
                        'positionId'  => $material['positionId'],
                    ],
                ]);
                if ($isPass === true && $json['warn'] == '新增成功') {
                    /***收发明细***/
                    $bool = $this->insertInventoryIn($returnMx);
                    if ($bool !== true) {
                        $json['warn'] = $bool;
                        goto resp;
                    }
                    $collection = find(array(
                        "table"  => self::tableMx,
                        "single" => "orderId = '" . $res['id'] . "' and return_num < num",
                        "field"  => " IFNULL(count(id),0) as num "
                    ));
                    if ($collection['num'] == 0) {
                        static::update([
                            'table' => self::table,
                            'field' => [
                                'state' => 3,
                            ],
                            'where' => " id = '{$res['id']}' ",
                        ]);
                    }
                    $this->commitTrans();//提交事务
                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], lang('toolCollection.returnEdit.log'));
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $_SESSION['warn'] = $json['warn'];
                    $json['warn']     = 2;
                    $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['orderId'];
                }
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 生成入库单
     */
    private function insertInventoryIn($returnMx): bool|string
    {
        $info  = query(self::table, " id = '$returnMx[orderId]' ");
        $id    = self::getId();
        $field = [
            'id'          => $id,
            'coid'        => self::$coid,
            'orderNo'     => codeTemplateClass::generateCode('inStock', [
                'prefix' => 'RKD' . date('Ymd'),
                'table'  => 'inventory_changes',
                'field'  => 'orderNo',
                'where'  => " and coid = '" . self::$coid . "'",
            ], []),
            'type'        => '其他入库',
            'classify'    => 1,
            'recordDate'  => $this->date,
            'confirmTime' => $this->date,
            'reviewTime'  => $this->date,
            'state'       => '已复核',
            'stid'        => self::$stid,
        ];
        $warn  = static::insert(array(
            'table' => 'inventory_changes',
            'field' => $field
        ));
        if ($warn != '新增成功') {
            return "新增入库单失败";
        }
        $mx   = $returnMx;
        $warn = static::insert(array(
            'table' => 'inventory_changes_detail',
            'field' => $fieldChangeMx = [
                'id'          => self::getId(),
                'coid'        => self::$coid,
                'orderId'     => $id,
                'materialId'  => $mx['materialId'],
                'orderNum'    => $mx['num'],
                'batch'       => $mx['batch'],
                'num'         => $mx['num'],
                'unit'        => $mx['unit'],
                'price'       => 0,
                'sourceTable' => self::tableReturn,
                'sourceId'    => $returnMx['id'],
                'sourceNo'    => $info['orderNo'],
                'warehouseId' => $mx['warehouseId'],
                'positionId'  => $mx['positionId'],
            ]
        ));
        if ($warn != '新增成功') {
            return "新增入库单明细失败";
        }
        //单位单价转换
        $mainUnitNum = inventoryBalanceClass::toMainUnit($mx['materialId'], $mx['num'], $mx['unit']);
        $recordId    = self::getNo();
        $warn        = insert([
            'table' => self::tableRecord,
            'field' => [
                'id'            => $recordId,
                'coid'          => self::$coid,
                'warehouseId'   => $mx['warehouseId'],
                'positionId'    => $mx['positionId'],
                'materialId'    => $mx['materialId'],
                'inventoryId'   => $id,
                'inventoryMxId' => $fieldChangeMx['id'],
                'batch'         => $mx['batch'],
                'num'           => $mainUnitNum,
            ],
        ]);
        if ($warn != '新增成功') {
            return "新增入库明细失败";
        }
        if (!empty($mx['positionId'])) inventoryBalanceClass::recordStockToLocation($recordId, ['positionId' => $mx['positionId']]);
        return true;
    }

    /**
     * 归还记录
     */
    public function returnRecord()
    {
        $id     = $this->post('id');
        $result = find(['table' => 'tool_collection_return', 'where' => "detail_id = '$id' order by list asc"]);
        $list   = '';
        if (empty($result['array'])) {
            $list .= '<div class="record">' . L('toolCollection.returnRecord.none') . '</div>';
        } else {
            foreach ($result['array'] as $array) {
                $list .= "<div class='record'>" . L('toolCollection.returnRecord.returnNum') . "：" . self::lostZero($array['num'], 'numPrecision') . "&emsp;" . L('toolCollection.returnRecord.returnTime') . "：{$array['time']}</div>";
            }
        }
        $html = $list;
        return $this->layer(["title" => L('toolCollection.returnRecord.eturnRecord'), "height" => 335, "width" => 750, "html" => $html]);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('toolCollection.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('toolCollection.delete.noChoice');
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
                if ($info['state'] != 0) {
                    $warn = L('toolCollection.delete.fail');
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => self::tableReturn, "where" => " orderId = '$id' "));
                    delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
                    //返回
                    $warn = L('toolCollection.delete.success');
                    $x++;
                }
                $text .= str_replace(['{{id}}'], [$info['id']], lang('toolCollection.delete.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], lang('toolCollection.delete.log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], lang('toolCollection.delete.warn'));
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function toolOverhaulRecordOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('toolCollection.edit.code') => text(array("name" => "code")),
                    L('toolCollection.edit.name')   => text(["name" => "name"]),
                    L('toolCollection.edit.batch') => text(["name" => "batch"]),
                ],
                [
                    L('toolCollection.edit.orderDate') => text(['name' => 'orderDate', 'laydate' => ['range' => '~', 'type' => 'date']]),
                    L('toolCollection.returnRecord.returnTime') => text(['name' => 'returnDate', 'laydate' => ['range' => '~', 'type' => 'date']]),
                    L('toolCollection.homeSearch.orderNo') => text(["name" => "orderNo"]),
                ],
                [
                    L('toolCollection.homeSearch.recipient') => text(['name' => 'recipient']),
                    L('toolCollection.edit.warehouse') => text(['name' => 'warehouse']),
                    L('toolCollection.edit.position') => text(['name' => 'position']),
                ]
            ]
        ]);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-工具领用归还明细-查询条件*/
    public function toolCollectionRecord()
    {
        $html = $this->toolOverhaulRecordOptions(false);
        //控件
        $button = "";
        if ($this->power('toolCollectionRecord', "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',exportFun:'exportRecord',classify:'工具领用归还明细'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function toolCollectionRecordSearch()
    {
        //查询结果
        $where = " a.coid = '" . self::$coid . "' and b.state > 0 ";
        $equal = [
            'b.type' => $this->post('type'),
        ];
        $like  = [
            'b.orderNo' => $this->post('orderNo'),
            'm.name'    => $this->post('name'),
            'code'      => $this->post('code'),
            'model'     => $this->post('model'),
            'a.batch'   => $this->post('batch'),
        ];
        //生成查询语句
        $where .= search([
            "="    => $equal,
            "like" => $like,
        ]);
        //领用日期
        if ($this->post('orderDate')) {
            $where = self::timeComparison($this->post('orderDate'), 'date', 'b.orderDate');
        }
        if ($this->post('returnDate')) {
            $where .= self::timeComparison($this->post('returnDate'), 'date', 'a.time');
        }
        if ($this->post('warehouse')) {
            $where .= " and a.warehouseId in (select id from warehouse where name like '%" . $this->post('warehouse') . "%') ";
        }
        if ($this->post('position')) {
            $where .= " and a.positionId in (select id from warehouse_position where name like '%" . $this->post('position') . "%') ";
        }
        if ($this->post('recipient')) {
            $where .= " and recipient in (select stid from staff where name like '%" . $this->post('recipient') . "%') ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page                                    = $this->page(array(
            "table" => "tool_collection_return as a join " . self::table . " as b on a.orderId = b.id join material as m on a.materialId = m.id",
            "field" => "a.*,b.orderNo,b.type,b.recipient,b.orderDate,m.code,m.name,m.model,m.typeId,m.typeName",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION['toolCollectionRecord']['sql'] = $page['sql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            $sourceMx  = query(self::tableMx, " id = '$array[detail_id]' ", "orderId,num,return_num");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'recipient':
                        $row[] = self::findStaff($array['recipient']);
                        break;
                    case 'warehouse':
                        $row[] = warehouseClass::getName($array['warehouseId']);
                        break;
                    case 'position':
                        $row[] = warehousePositionClass::getName($array['positionId']);
                        break;
                    case 'pickNum':
                        $row[] = self::lostZero($sourceMx['num'], 'numPrecision');
                        break;
                    case 'num':
                        $row[] = self::lostZero($array['num'], 'numPrecision');
                        break;
                    case 'state':
                        $state     = $sourceMx['num'] > $sourceMx['return_num'] ? '部分归还' : '已归还';
                        $row[] = $state;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => "tool_collection_return as a join " . self::table . " as b on a.orderId = b.id join material as m on a.materialId = m.id",
            'single' => $where,
            'field'  => "ifnull(sum(a.num),0) as num",
        ]);
        $sourceMx = find([
            'table'  => self::tableMx,
            'single' => " id in (select a.detail_id from tool_collection_return as a join " . self::table . " as b on a.orderId = b.id join material as m on a.materialId = m.id where {$where}) ",
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'pickNum'   => self::lostZero($sourceMx['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportRecord()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power('toolCollectionRecord', 'export')) {
            $_SESSION['warn'] = L('toolCollection.homeSearch.power');
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => "tool_collection_return as a join " . self::table . " as b on a.orderId = b.id join material as m on a.materialId = m.id",
                    "field" => "a.*,b.orderNo,b.type,b.recipient,b.orderDate,m.code,m.name,m.model,m.typeId,m.typeName",
                    "where" => "a.id in ('".implode("','", $checkedId)."') order by a.time desc",
                ))['array'];
            }else{
                $sql    = $_SESSION['toolCollectionRecord']['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $sourceMx  = query(self::tableMx, " id = '$array[detail_id]' ", "orderId,num,return_num");
                $recipient = self::findStaff($array['recipient']);
                $state     = $sourceMx['num'] > $sourceMx['return_num'] ? '部分归还' : '已归还';
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '物料编码'=>$array['code'],
                            '物料名称'=>$array['name'],
                            '分类'=>$array['typeName'],
                            '规格型号'=>$array['model'],
                            '单位'=>$array['unit'],
                            '单据编号'=>$array['orderNo'],
                            '领用人'=>$recipient,
                            '领用类型'=>$array['type'],
                            '仓库'=>warehouseClass::getName($array['warehouseId']),
                            '库位'=>warehousePositionClass::getName($array['positionId']),
                            '领用日期'=>$array['orderDate'],
                            '领用数量'=> self::lostZero($sourceMx['num'], 'numPrecision'),
                            '归还时间'=>$array['time'],
                            '归还数量'=> self::lostZero($array['num'], 'numPrecision'),
                            '批次'=>$array['batch'],
                            '状态'=>$state,
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }

            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('toolCollection.homeSearch.logReturn'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title . ".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }
    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            '工具领用归还明细'=>[
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'分类',
                    'aliasName'=>'分类',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'领用人',
                    'aliasName'=>'领用人',
                ],
                [
                    'columnName'=>'领用类型',
                    'aliasName'=>'领用类型',
                ],
                [
                    'columnName'=>'仓库',
                    'aliasName'=>'仓库',
                ],
                [
                    'columnName'=>'库位',
                    'aliasName'=>'库位',
                ],
                [
                    'columnName'=>'领用日期',
                    'aliasName'=>'领用日期',
                ],
                [
                    'columnName'=>'领用数量',
                    'aliasName'=>'领用数量',
                ],
                [
                    'columnName'=>'归还时间',
                    'aliasName'=>'归还时间',
                ],
                [
                    'columnName'=>'归还数量',
                    'aliasName'=>'归还数量',
                ],
                [
                    'columnName'=>'批次',
                    'aliasName'=>'批次',
                ],
                [
                    'columnName'=>'状态',
                    'aliasName'=>'状态',
                ],
            ],
            default=>  [
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'领用人',
                    'aliasName'=>'领用人',
                ],
                [
                    'columnName'=>'领用日期',
                    'aliasName'=>'领用日期',
                ],
                [
                    'columnName'=>'领用数量',
                    'aliasName'=>'领用数量',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
                [
                    'columnName'=>'状态',
                    'aliasName'=>'状态',
                ],
            ]
        };
    }
}
